package com.tedu.bank_ems.dao.impl;

import com.tedu.bank_ems.dao.UserDao;
import com.tedu.bank_ems.entity.User;

import java.sql.*;

/**
 * Author：毕龙
 * Date: 2024/6/24 11:36
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User getUserByUsername(String username) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        try {
            //加载驱动
            //通过一个类的信息获取类对象 类加载
            Class.forName("com.mysql.cj.jdbc.Driver");

            //获取链接
            String url = "jdbc:mysql://localhost:3306/ems";
            String mysqlUser = "root";
            String mysqlPass = "root";
            conn = DriverManager.getConnection(url, mysqlUser, mysqlPass);

            //执行sql
            String sql = "select id, username, realname, password, sex from user where username = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1,username);
            //处理查询结果
            rs = pstm.executeQuery();
            if (rs.next()){
                user = new User();
                user.setId(rs.getInt(1));
                user.setUsername(rs.getString(2));
                user.setNickname(rs.getString(3));
                user.setPassword(rs.getString(4));
                user.setSex(rs.getString(5));
            }


            //释放资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                rs.close();
                pstm.close();
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        return user;
    }
}
